import 'dart:convert';
import 'dart:io';
import 'dart:typed_data';

import 'package:flustars/flustars.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:get/get.dart';
import 'package:zrjz/api/auth_repository.dart';
import 'package:zrjz/comm/utils/log_utils.dart';
import 'package:zrjz/entity/response/verify_code.dart';

import 'verify_code_dialog_state.dart';

class VerifyCodeDialogController extends GetxController {
  final AuthRepository authRepository = Get.find();
  final VerifyCodeDialogState state = VerifyCodeDialogState();

  /// 获取验证码Code图片
  Future<void> fetchVerifyCodeImg() async {
    //请求数据
    var result = await authRepository.getVerifyCodeImage();

    //处理数据
    if (result.isSuccess) {
      VerifyCode? verifyCode = result.data;
      state.imageKey = verifyCode?.key;
      //拿到 Base64 图片存入到本地File，便于缓存

      final bytes = base64.decode(verifyCode?.img?.replaceFirst('data:image/png;base64,', '') ?? '');
      final tempDir = DirectoryUtil.getTempPath();
      final file = File('$tempDir/verify${DateTime.now().millisecondsSinceEpoch}.png');
      await file.writeAsBytes(bytes);
      Log.d('存入的File路径为：${file.path}');
      state.imgFilePath = file.path;

      update();
    } else {
      String? errorMsg = result.errorMsg;
      SmartDialog.showToast(errorMsg ?? '未知错误'.tr);
    }
  }

  @override
  void onReady() {
    super.onReady();
    fetchVerifyCodeImg();
  }

  @override
  void onClose(){
    _clearCachedImage();
    super.onClose();
  }

  // 清除缓存的verify验证图形码的缓存文件
  Future<void> _clearCachedImage() async {
    final cacheDir = await DirectoryUtil.initTempDir();
    if (cacheDir != null) {
      if (await cacheDir.exists()) {
        //遍历删除 Cache 目录下面的全部文件或文件夹
        for (final entity in cacheDir.listSync()) {
          // 如果是指定的文件直接删除
          if (entity is File && entity.path.split('/').last.startsWith("verify")) {
            await entity.delete();
          }
        }
      }
    }
  }

}
